const express = require('express');
const CONFIG = require('./config/config');

const app = express();

//配置cors跨域
const cors = require('cors');
app.use(cors());

//配置资源路径
app.use(express.static('public'));
app.get('/uploads', function (req, res) {
    console.log(req.url);
});

//配置JWT身份认证
const expressJWT = require('express-jwt');
let unlesspath = [
    '/api/member/register',
    '/api/member/login',
    '/api/goods/getlist',
    '/api/goods/getinfo'
];
app.use(expressJWT({ secret: CONFIG.JWT_SECRET, algorithms: ['HS256'] }).unless({ path: unlesspath }));

//配置解析表单数据 - 将 post 提交的 键值对格式的数据 装入 req.body
app.use(express.urlencoded({ extended: false }));

//配置各模块路由
const memberRouter = require('./router/member');
app.use('/api', memberRouter);
const goodsRouter = require('./router/goods');
app.use('/api', goodsRouter);
const cartRouter = require('./router/cart');
app.use('/api', cartRouter);


app.use((err, req, res, next) => {
    if (err.name === 'UnauthorizedError') {
        return res.send(CONFIG.USER_JWT_ERROR);
    }
    // 其他异常
    res.send({
        status: 1,
        message: err.message
    })
});


//配置端口
app.listen(80, function () {
    console.log('server running at http://localhost:80...');
});